//
//  GestureLockView.swift
//  ezyform
//
//  Created by Moennig Q on 19/7/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
enum GestureResultType: Int{
    case atLeast5 = 0//至少5个点
    case redraw //手势不匹配需要redraw
    case toConfirmGesture//确认成功
    case bingo
}
protocol GestureLockProtocol: NSObjectProtocol {
    func gestureLockSuccess(tagArray: [Int])
}
class GestureLockView: UIView {
    let atLeastPoints: Int = 5//手势至少5个数字
    let maxUnlockCount: Int = 5//解锁此时最多5次
    var tryUnLockCnt: Int = 0//已经尝试解锁的次数
    // MARK: - Properties
    weak var gestureLockDelegate: GestureLockProtocol?
    
    let screenWidth = UIScreen.main.bounds.size.width
    var btnArray:[UIButton] = [UIButton]()
    
    var selectBtnTagArray:[Int] = [Int]()   //选中的按钮 的tag值
    var gesturePoint:CGPoint = CGPoint()    //手势中手指当前 的位置
    let btnWH:CGFloat = 60                  //按钮的宽高
    let btnImgNormal = "gesturesetting_unsel"
    let btnImgSelected =  "gesturesetting_sel"
    var gestureLockViewHeight: CGFloat = 0
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - Lifecycle
    override init(frame:CGRect) {
        super.init(frame: frame)
        gestureLockViewHeight = self.screenWidth - (self.screenWidth - self.btnWH * 3) / 4 * 2
        self.initButtons()
    }
    // MARK: - PrivateMethod
    private func initButtons() { 
        self.backgroundColor = .clear
        for i in 0...8 {
            //第几行
            let row = i / 3
            let loc = i % 3
            
            //两个button的间距
            let btnSpace = (screenWidth - 3*btnWH)/4
            let btnX = btnSpace + (btnWH + btnSpace) * CGFloat(loc)
            let btnY = (btnWH + btnSpace) * CGFloat(row)
            
            let gestureNodeBtn = UIButton(frame:CGRect(x: btnX,y: btnY,width: btnWH, height: btnWH))
            gestureNodeBtn.tag = i
            gestureNodeBtn.isUserInteractionEnabled = false   //不响应用户的交互。一定要加上这句
            gestureNodeBtn.setImage(UIImage(named: btnImgNormal), for: .normal)
            self.addSubview(gestureNodeBtn)
            btnArray.append(gestureNodeBtn)
        }
    }
    override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext() //获取画笔上下文
        
        var i = 0
        for tag in selectBtnTagArray {
            if (0 == i) {
                //开始画线,设置直线的起点坐标
                context?.move(to: CGPoint(x: btnArray[tag].center.x, y: btnArray[tag].center.y))
                
            } else {
                //画直线,设置直线的终点坐标
                context?.addLine(to: CGPoint(x: btnArray[tag].center.x,y: btnArray[tag].center.y))
            }
            i = i+1
        }
        
        //如果有选中的节点，就取 跟着 手指的滑动 画线
        if (selectBtnTagArray.count > 0) {
            // 移除最后一条多余的线，
            if gesturePoint != CGPoint(x: 0, y: 0) {
                context?.addLine(to: CGPoint(x: gesturePoint.x, y: gesturePoint.y))
            }
        }
        context?.setLineWidth(2)      //设置画笔宽度
        context?.setLineJoin(.round)  //两个线相交点 平滑处理
        context?.setLineCap(.round) //设置线条两端的样式为圆角
        context?.setStrokeColor(UIColor(hexStr: Constant.ThemeColorHexStr).cgColor)
        context?.strokePath()
    }
    
    // MARK: - Override
    // 当手指接触屏幕时，就会调用touchesBegan:withEvent方法；
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        selectBtnTagArray.removeAll()
        touchesChange(touches)
    }
    
    //当手指在屏幕上移动时，调用touchesMoved:withEvent方法；
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        touchesChange(touches)
    }
    
    //当触摸被取消（比如触摸过程中被来电打断），就会调用touchesCancelled:withEvent方法。
    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        
    }
    //当手指离开屏幕时，就会调用touchesEnded:withEvent方法；
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        gestureLockDelegate?.gestureLockSuccess(tagArray: self.selectBtnTagArray)
        gesturePoint = CGPoint(x: 0, y: 0);
        self.setNeedsDisplay()
    }
    
    private func touchesChange(_ touches: Set<UITouch>) {
        //获取 触摸对象 ,触摸对象的位置坐标来实现
        gesturePoint = touches.first!.location(in: self)
        
        for btn in btnArray {
            //判断 手指的坐标 是否在 button的坐标里
            if !selectBtnTagArray.contains(btn.tag) && btn.frame.contains(gesturePoint) {
                //处理跳跃连线
                var lineCenterPoint:CGPoint = CGPoint()
                
                if selectBtnTagArray.count > 0 {
                    lineCenterPoint = centerPoint(startPoint: btn.frame.origin, endPoint: btnArray[selectBtnTagArray.last!].frame.origin)
                }
                
                //保存中间跳跃 过的节点
                for btn in btnArray {
                    if  !selectBtnTagArray.contains(btn.tag) && btn.frame.contains(lineCenterPoint)  {
                        btn.setImage(UIImage(named: btnImgSelected), for: .normal)
                        selectBtnTagArray.append(btn.tag)
                    }
                }
                
                //保存划过的按钮的tag
                selectBtnTagArray.append(btn.tag)
                btn.setImage(UIImage(named: btnImgSelected), for: .normal)
            }
        }
        
        //setNeedsDisplay会自动调用drawRect方法 进行画线
        self.setNeedsDisplay()
    }
    
    //计算2个节点中心的坐标
    private func centerPoint(startPoint: CGPoint, endPoint:CGPoint) -> CGPoint {
        let rightPoint = startPoint.x > endPoint.x ? startPoint.x : endPoint.x
        let leftPoint = startPoint.x < endPoint.x ? startPoint.x : endPoint.x
        
        let topPoint = startPoint.y > endPoint.y ? startPoint.y : endPoint.y
        let bottomPoint = startPoint.y < endPoint.y ? startPoint.y : endPoint.y
        
        //x坐标： leftPoint +（rightPoint-leftPoint)/2 = (rightPoint+leftPoint)/2
        return CGPoint(x: (rightPoint + leftPoint)/2 + btnWH/2, y: (topPoint + bottomPoint)/2 + btnWH/2);
    }
    
    func recoverNodeStatus() {
        selectBtnTagArray.removeAll()
        for btn in btnArray {
            btn.setImage(UIImage(named: btnImgNormal), for: .normal)
        }
        self.setNeedsDisplay()
    }
    
}
